<template>
  <div class="">
    <public-dialog :title="titleName" width="50%" dialogCenter :visible="visible" :footer-button="showButton"
      @update:visible="onVisibleChange" @onConfirm="confirmHandler">
      <el-form :model="formInline" label-width="130" ref="formRef" @submit.native.prevent
        :rules="formInline.specialType === 1 ? formRules2 : formRules" :validate-on-rule-change="false"
        style="height: 70vh;overflow: auto;padding-right: 10px;" :disabled="titleName === '开票信息'" v-loading="loading"
        element-loading-text="加载中...">
        <div class="head-title">
          <span>基本信息</span>
        </div>
        <el-row>
          <el-col :span="12">
            <el-form-item label="业务名称" prop="business.businessName">
              <el-input v-model="formInline.business.businessName" placeholder="请输入业务名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="business.projectName">
              <el-input v-model="formInline.business.projectName" placeholder="请输入项目名称" clearable disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同名称" prop="business.contractName">
              <el-input v-model="formInline.business.contractName" placeholder="请输入合同名称" clearable disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同编号" prop="business.contractNumber">
              <el-input v-model="formInline.business.contractNumber" placeholder="请输入合同编号" clearable disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资源名称" prop="business.resourceName">
              <el-input v-model="formInline.business.resourceName" placeholder="请输入资源名称" clearable disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资源位置" prop="business.resourceLocation">
              <el-input v-model="formInline.business.resourceLocation" placeholder="请输入资源位置" clearable disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="承租方" prop="business.lessee">
              <el-input v-model="formInline.business.lessee" placeholder="请输入承租方" clearable disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="租赁面积" prop="business.leaseArea">
              <el-input v-model="formInline.business.leaseArea" placeholder="请输入租赁面积" clearable disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开票金额" prop="business.invoicedAmount">
              <el-input v-model="formInline.business.invoicedAmount" placeholder="请输入开票金额" clearable
                @input="formInline.business.invoicedAmount = limitInputNum(formInline.business.invoicedAmount, 9, 2, true)" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="内部备注" prop="business.internalRemark">
              <el-input v-model="formInline.business.internalRemark" placeholder="请输入内部备注" type="textarea" maxlength="50"
                show-word-limit rows="3" resize="none" />
            </el-form-item>
          </el-col>
        </el-row>
        <div class="head-title">
          <span>发票信息</span>
        </div>
        <el-row>
          <el-col :span="12">
            <el-form-item label="发票类型" prop="receiptType">
              <el-select v-model="formInline.receiptType" placeholder="请选择发票类型" clearable style="width: 100%;">
                <el-option label="数电普通发票" :value="1" />
                <el-option label="数电专用发票" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="特殊票种" prop="specialType">
              <el-select v-model="formInline.specialType" placeholder="请选择特殊票种" clearable style="width: 100%;">
                <el-option label="否" :value="0" />
                <el-option label="不动产租赁" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <template v-if="formInline.specialType === 1">
            <el-col :span="12">
              <el-form-item label="不动产地址" prop="specialType1Info.realEstateAddress">
                <el-input v-model="formInline.specialType1Info.realEstateAddress" placeholder="请输入不动产地址" maxlength="50"
                  show-word-limit clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="租赁起止日" prop="specialType1Info.leaseTime">
                <el-date-picker v-model="formInline.specialType1Info.leaseTime" type="daterange" range-separator="-"
                  start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="跨地（市）标识" prop="specialType1Info.isCross">
                <el-select v-model="formInline.specialType1Info.isCross" placeholder="请选择是否为跨地（市）标识" clearable
                  style="width: 100%;">
                  <el-option label="否" :value="0" />
                  <el-option label="是" :value="1" />
                </el-select>
              </el-form-item>
            </el-col>
          </template>
          <el-col :span="24">
            <el-form-item label="发票备注" prop="receiptRemark">
              <el-input v-model="formInline.receiptRemark" placeholder="请输入发票备注" type="textarea" maxlength="50"
                show-word-limit rows="3" resize="none" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="margin-top: 20px;">
          <el-col :span="1"></el-col>
          <el-col :span="1" style="display: flex;justify-content: right;align-items: center;">
            <span style="writing-mode: vertical-lr;letter-spacing: 15px;">购买方信息</span>
          </el-col>
          <el-col :span="10">
            <el-form-item label="购方名称" prop="buyer.name">
              <el-input v-model="formInline.buyer.name" placeholder="请输入购方名称" clearable />
            </el-form-item>
            <el-form-item label="购方识别号" prop="buyer.idNumber">
              <el-input v-model="formInline.buyer.idNumber" placeholder="请输入购方识别号" clearable />
            </el-form-item>
            <el-form-item label="购方地址" prop="buyer.address">
              <el-input v-model="formInline.buyer.address" placeholder="请输入购方地址" clearable />
            </el-form-item>
            <el-form-item label="购方电话" prop="buyer.phone">
              <el-input v-model="formInline.buyer.phone" placeholder="请输入购方电话" clearable />
            </el-form-item>
            <el-form-item label="购方银行" prop="buyer.bankName">
              <el-input v-model="formInline.buyer.bankName" placeholder="请输入购方银行" clearable />
            </el-form-item>
            <el-form-item label="购方账号" prop="buyer.bankAccount">
              <el-input v-model="formInline.buyer.bankAccount" placeholder="请输入购方账号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="1" style="display: flex;justify-content: right;align-items: center;">
            <span style="writing-mode: vertical-lr;letter-spacing: 15px;">销售方信息</span>
          </el-col>
          <el-col :span="10">
            <el-form-item label="销方名称" prop="seller.name">
              <el-input v-model="formInline.seller.name" placeholder="请输入销方名称" clearable  />
            </el-form-item>
            <el-form-item label="销方识别号" prop="seller.idNumber">
              <el-input v-model="formInline.seller.idNumber" placeholder="请输入销方识别号" clearable  />
            </el-form-item>
            <el-form-item label="销方地址" prop="seller.address">
              <el-input v-model="formInline.seller.address" placeholder="请输入销方地址" clearable  />
            </el-form-item>
            <el-form-item label="销方电话" prop="seller.phone">
              <el-input v-model="formInline.seller.phone" placeholder="请输入销方电话" clearable  />
            </el-form-item>
            <el-form-item label="销方银行" prop="seller.bankName">
              <el-input v-model="formInline.seller.bankName" placeholder="请输入销方银行" clearable  />
            </el-form-item>
            <el-form-item label="销方账号" prop="seller.bankAccount">
              <el-input v-model="formInline.seller.bankAccount" placeholder="请输入销方账号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="1"></el-col>
        </el-row>
      </el-form>
    </public-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick } from "vue";
import { ElForm, ElFormItem, ElRow, ElCol, ElInput, ElSelect, ElOption, ElNotification, ElDatePicker, ElLoading } from "element-plus";
import PublicDialog from "@/components/PublicDialog.vue";
import { limitInputNum } from "@/common/utils/GlobalUtils.js";
import { invoiceApi } from "@/api/assets.js";
import { debounce } from "lodash";

import { useRoute } from "vue-router";
const route = useRoute();

let titleName = ref("");
let visible = ref(false);
let loading = ref(false);

let typeOptions = ref([
  {
    label: "数电普通发票",
    value: 0
  },
  {
    label: "数电专用发票",
    value: 1
  },
]);
let specialOptions = ref([
  {
    label: "否",
    value: 0
  },
  {
    label: "不动产租赁",
    value: 1
  },
]);

let formInline = reactive({
  business: {},
  buyer: {},
  seller: {},
  specialType1Info: {},
});
let formRules = reactive({
  "business.businessName": [{ required: true, message: "请输入业务名称", trigger: "blur" }],
  "business.projectName": [{ required: true, message: "请输入项目名称", trigger: "blur" }],
  "business.contractName": [{ required: true, message: "请输入合同名称", trigger: "blur" }],
  "business.contractNumber": [{ required: true, message: "请输入合同编号", trigger: "blur" }],
  "business.resourceName": [{ required: true, message: "请输入资源名称", trigger: "blur" }],
  "business.resourceLocation": [{ required: true, message: "请输入资源位置", trigger: "blur" }],
  "business.lessee": [{ required: true, message: "请输入承租方", trigger: "blur" }],
  "business.leaseArea": [{ required: true, message: "请输入租赁面积", trigger: "blur" }],
  "business.invoicedAmount": [{ required: true, message: "请输入开票金额", trigger: "blur" }],
  "business.internalRemark": [{ required: true, message: "请输入内部备注", trigger: "blur" }],
  receiptType: [{ required: true, message: "请选择发票类型", trigger: "change" }],
  specialType: [{ required: true, message: "请选择特殊票种", trigger: "change" }],
  "buyer.name": [{ required: true, message: "请输入购方名称", trigger: "blur" }],
  "buyer.idNumber": [{ required: true, message: "请输入购方识别号", trigger: "blur" }],
  "seller.name": [{ required: true, message: "请输入销方名称", trigger: "blur" }],
  "seller.idNumber": [{ required: true, message: "请输入销方识别号", trigger: "blur" }],
});
let formRules2 = {
  ...formRules,
  "specialType1Info.realEstateAddress": [{ required: true, message: "请输入不动产地址", trigger: "change" }],
  "specialType1Info.leaseTime": [{ required: true, message: "请选择租赁起止日", trigger: "change" }],
  "specialType1Info.isCross": [{ required: true, message: "请选择是否为跨地（市）标志", trigger: "change" }],
}
let formRef = ref(null);

let showButton = ref(true);
let onVisibleChange = (booleanValue) => {
  if (!booleanValue) {
    formRef.value.resetFields();
  }
  visible.value = booleanValue;
};

let emits = defineEmits(["success"]);
let _debounce = debounce(async () => {
  let params = { ...formInline };
  if (params.specialType === 1 && params.specialType1Info.leaseTime) {
    params.specialType1Info["leaseBeginDate"] = params.specialType1Info.leaseTime[0];
    params.specialType1Info["leaseEndDate"] = params.specialType1Info.leaseTime[1];
  }
  let res = await invoiceApi.addInvoice(formInline);
  if (res.code === "200") {
    ElNotification.success("申请成功");
    emits("success");
    visible.value = false;
  }
}, 500, { leading: true, trailing: false });
let confirmHandler = () => {
  if (loading.value) {
    return
  }
  formRef.value.validate(async valid => {
    if (valid) {
      _debounce();
    }
  })
};

let openHandler = async (title, row) => {
  loading.value = true;
  visible.value = true;
  titleName.value = title;
  if (row) {
    // 详情
    showButton.value = false;
    let res = await invoiceApi.getInfo({ receiptId: row.receiptId }).catch(err => {
      loading.value = false;
    });
    if (res.data) {
      nextTick(() => {
        for (let key in res.data) {
          if (key === "specialType1Vo" && res.data[key]) {
            let info = res.data[key];
            formInline["specialType1Info"] = info;
            formInline["specialType1Info"]["leaseTime"] = [info.leaseBeginDate, info.leaseEndDate];
          } else {
            formInline[key] = res.data[key];
          }
        }
      })
    }

  } else {
    // 申请开票
    showButton.value = true;
    let res = await invoiceApi.getBasicInfo({ contractId: route.params.contractId }).catch(err => {
      loading.value = false;
    });
    if (res.data) {
      let business = res.data.businessVo;
      let seller = res.data.companyVo;
      nextTick(() => {
        for (let key in business) {
          formInline.business[key] = business[key];
        }
        for (let key in seller) {
          formInline.seller[key] = seller[key];
        }
      })
    }
  }
  loading.value = false;
};

defineExpose({
  openHandler
});
</script>

<style lang="scss" scoped>
.head-title {
  padding-bottom: 20px;
  padding-top: 10px;
  color: #1A1A1A;
  font-size: 17px;
  font-family: SourceHanSansMedium;
  font-weight: bold;
}
</style>
